import random
import math
# 将数据分为M份，一份为测试，剩下的M-1份训练集
def SplitData(data, M, K, seed):
    test = []
    train =[]
    random.seed(seed)
    for user, item in data:
        if random.randint(0, M) == K:
            test.append([user, item])
        else:
            train.append([user, item])
    return train, test

def GetRecommendation(user, N):
    print()
'''
描述了推荐的商品中用户真正喜欢的商品占用户所有真正喜欢的商品的比例
'''
def Recall(train, test, N):
    hit = 0
    all = 0
    for user in train.keys():
        # 用户真正喜欢的商品
        tu = test[user]
        rank = GetRecommendation(user, N)
        for item, pui in rank:
            if item in tu:
                hit += 1
        all += len(tu)
    return hit/ (all*1.0)
'''
描述了推荐的商品中用户真正喜欢的商品所占比例
'''
def Precision(train, test, N):
    hit = 0
    all = 0
    for user in train.keys():
        tu = test[user]
        rank = GetRecommendation(user, N)
        for item, pui in rank:
            if item in tu:
                hit += 1
        all += N
    return hit / (all * 1.0)
'''
查看推荐商品的流行度：
1.计算所有商品的流行度
2.计算推荐商品的流行度 -> 如果推荐出的商品都很热门，说明推荐的新颖度很低，否则，比较新颖
'''
def Popularity(train, test, N):
    item_popularity = dict()
    for user, items in train.items():
        for item in items.keys():
            if item not in item_popularity:
                item_popularity[item] = 0
                item_popularity[item] += 1
    ret = 0
    n = 0
    for user in train.keys():
        rank = GetRecommendation(user, N)
        for item, pui in rank:
            ret += math.log(1 + item_popularity[item])
            n += 1
    ret /= n * 1.0
    return ret